<?php
class MenuModel extends Model{
	
	protected $_auto = array (
		array('status','1'),  // 新增的时候把status字段设置为1
	);
	
	protected $_validate = array(
		array('name','require','name required'), 
		array('pid','require',' pid required'), 
		array('name','','name exist!',0,'unique',1), 
	);
	
	
	
	/**
	 * @desc get all top level menu
	 * 
	 * @return array menus
	 */
	public function getTopMenu(){
		
		$where['status'] = 1;
		$where['pid'] = 0;
		$menus = $this->where($where)->order("sort desc")->select();
		return $menus;
	} 
	
	/**
	 * @desc get level 2 menu
	 * 
	 * @return array menus
	 */
	public function get2ndMenu($pid){
		
		$where['status'] = 1;
		$where['level']  = 2;
		$where['pid']    = $pid;
		$menus = $this->where($where)->order("sort desc")->select();
		return $menus;
		
	}
	
	/**
	 * @desc get all top and 2nd menu
	 */
	public function getNavMenu(){
		$where['status'] = 1;
		$where['level']  = array("LT",3);
		$menus = $this->where($where)->order("sort desc")->select();
		return $menus;
	}
	
	/**
	 * @desc get all sub menu of 2th level
	 * 
	 * @param int $pid
	 * @return array menus
	 */
	public function getSubMenu( $pid ){
		
		$where['level'] = 2;  //level 2
		$where['status'] = 1;
		$where['pid'] = $pid; 
		$menus = $this->where($where)->order("sort desc")->select(); 
		
		$subWhere['status'] = 1;
		$subWhere['level'] = 3;
		 
		foreach($menus as $k =>$v){  //level 3
			$subWhere['pid'] = $v['id'];
			$subMenu = $this->where($subWhere)->order("sort desc")->select();
			$menus[$k]['sub'] = $subMenu;
		}
		
		return $menus;
		
	}
	
	/**
	 * @get all menus 
	 */
	public function getAllMenu(){
		return $this->order("sort desc")->select();
	}
	
	public function getByIds($ids=''){
		if(empty($ids)){
			return false;
		}
		$where['id'] =  array('in',$ids);
		$where['status'] = 1;
		
		return $this->where($where)->order('sort desc')->select();
	}
	
	/**
	 * 查询角色拥有的菜单id
	 * 
	 * @param 角色id $roleid
	 */
	public function getByRoleid($roleid){
		if(empty($roleid)){
			return false;
		}
		$RoleModel = M('Role');
		$ids = $RoleModel->field('menus')->where('id='.$roleid)->find();
		return $this->getByIds($ids['menus']);
	}
}

?>